/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MessageIO;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * MulticastSender uses multicasting to broadcast messages using a multicast
 * datagram
 * @author Mark
 */
public class MulticastSender implements Runnable
    {
    private byte[] messageBytes;//message in bytes

    /**
     * Creates a new MulticastSender
     * @param bytes message in bytes
     */
    public MulticastSender(byte[] bytes)
        {
        super();
        messageBytes = bytes;//sets the message
        }

    /**
     * Delivers message using multicast
     */
    public void run()
        {
        try//attempt to deliver message
            {
            //Creates a DatagramSocket to send through MULTICAST_SENDING_PORT
            DatagramSocket socket = new DatagramSocket(
                    SocketConstants.MULTICAST_SENDING_PORT);
            //Gets the group using InetAddress and the MULICAST_ADDRESS
            InetAddress group = InetAddress.getByName(
                    SocketConstants.MULTICAST_ADDRESS);
            //Creates a datagrampacket containing message
            DatagramPacket packet = new DatagramPacket(messageBytes,
                    messageBytes.length, group,
                    SocketConstants.MULTICAST_LISTENING_PORT);
            //Sends and closes socket
//            System.out.println("Sent " + new String(messageBytes));
            socket.send(packet);
            socket.close();
            }
        catch (IOException io)
            {
            io.printStackTrace();
            }
        }
    }
